package pl.edu.agh.uddiProxy.server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

public class CacheThread extends Thread {
	private static final int LIFE_TIME = 600000;		//10 min
	private Map<CacheQuery, List<Map<String, String>>> cacheMap = new HashMap<CacheQuery, List<Map<String, String>>>();
	private static CacheThread cacheThread;
	private static Logger logger = Logger.getLogger(CacheThread.class);
	
	private CacheThread() {
	}
	
	public static CacheThread getInstance() {
		if (cacheThread == null) {
			cacheThread = new CacheThread();
			cacheThread.setDaemon(true);
		}
		return cacheThread;
	}

	@Override
	public void run() {
		clearCache();
		try {
			sleep(LIFE_TIME / 2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private synchronized void clearCache() {
		long now = System.currentTimeMillis();
		for (CacheQuery query : cacheMap.keySet()) {
			if (query.getTime() + LIFE_TIME >= now) {
				cacheMap.remove(query);
			}
		}
	}
	
	public synchronized boolean contains(String query, Map<String, String> staticMap) {
		CacheQuery cacheQuery = new CacheQuery(query, staticMap);
		boolean b = cacheMap.keySet().contains(cacheQuery);
		if (b) {
			logger.info("from cache");
		}
		return b;
	}
	
	public synchronized void add(String query, Map<String, String> staticMap, List<Map<String, String>> result) {
		CacheQuery cacheQuery = new CacheQuery(query, staticMap);
		cacheMap.put(cacheQuery, result);
	}
	
	public List<Map<String, String>> get(String query, Map<String, String> staticMap) {
		CacheQuery cacheQuery = new CacheQuery(query, staticMap);
		return cacheMap.get(cacheQuery);
	}
}
